#!/usr/bin/python
import os
import sys
import MySQLdb
import string
import time

def getResourceLeft(): 
   return 0


def isDigtal(myNum):
    nums = string.digits
    if type(myNum) is not str:
        return False
    else:
        for temp in myNum:
            if temp not in nums:
                return False
        return True


def connectDB():
    connect=MySQLdb.connect(host="localhost",port=3306,user="cloud",passwd="cloudpass",db="cloud")
    return connect

def cursorDB(connect):
    conn=connect.cursor()
    return conn

def closeConnect(connect):
    connect.close()

def closeCursor(cursor):
    cursor.close()

        
def checkParameter(conn):

    global env_id

    if not conn:
        print "Can not connect to database, Fail!"
        return -1
    paraCnt=len(sys.argv)
    if paraCnt != 2:
        return 0
    
    env_id=str(sys.argv[1])
    if not isDigtal(env_id):
        return 0
    
    flag = conn.execute("select env_id from mpi_env where env_id = " + env_id);
    if flag == 0:
        print "No Job ", env_id
        return -1
    return 1
    

def delJobs(env_id):
     
    tmp = str(time.time()).split('.')
    thistime=tmp[0]
    connect=connectDB()
    conn=cursorDB(connect)
    conn.execute("update mpi_env set status = 'finish' where env_id="+env_id)
    conn.execute("update mpi_env set end_time = " + thistime + " where env_id = " + env_id)
    conn.execute("select vm_id from env_resource where env_id="+env_id)
    
    rows=conn.fetchall()
    closeCursor(conn)
    closeConnect(connect)
    print rows  
    print "Job "+env_id+" is deleted!"

env_id="0"
str_command="command format:\n" + \
"   cjob job_id\n" + \
"   For example: cjob 1"

if __name__ == "__main__":
    connect=connectDB()
    conn=cursorDB(connect)
    flag = checkParameter(conn)
    closeCursor(conn)
    closeConnect(connect)
    if flag == -1:
        sys.exit(0)
    if flag == 0:
        print str_command
        sys.exit(0)
    delJobs(env_id) 

